#pragma once

#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

namespace net_work
{
    const int defaultbacklog = 5;
    const int defaultsockfd = -1;

    enum{
        SocketError = 1,
        BindError,
        ListenError,
        AcceptError
    };

    class Socket
    {
    public:
        virtual ~Socket() {}
        // 创建sockfd
        virtual void CreateSocketOrDie() = 0;
        // 绑定sockfd
        virtual void BindSocketOrDie(uint16_t port) = 0;
        // 监听sockfd
        virtual void ListenSocketOrDie(int backlog) = 0;
        // 接受链接
        virtual Socket *AcceptConnection(string *peerip, uint16_t *peerport) = 0;
        // 建立链接
        virtual bool ConnectServer(string &serverip, uint16_t serverport) = 0;
        // 获取套接字
        virtual int GetSockfd() = 0;
        // 设置套接字
        virtual void SetSockfd(int &sockfd) = 0;
        // 关闭sockfd
        virtual void CloseSocket() = 0;
        // 接受
        virtual bool Recv(string *buffer, int size) = 0;
        // 发送
        virtual void Send(string &send_str) = 0;
        // 设置sockfd属性
        virtual void ReUseAddr() = 0;
        // TO DOING
    public:
        // 建立监听sockfd
        void BuildListenSocketMethod(uint16_t port, int backlog)
        {
            CreateSocketOrDie();
            ReUseAddr();
            BindSocketOrDie(port);
            ListenSocketOrDie(backlog);
        }
        // 建立链接sockfd
        bool BuildConnectSocketMethod(string &serverip, uint16_t serverport)
        {
            CreateSocketOrDie();
            return ConnectServer(serverip, serverport);
        }
        // 设置sockfd
        void BuildNormalSocketMethod(int sockfd)
        {
            SetSockfd(sockfd);
        }
    };

    class TcpSockfd : public Socket
    {
    public:
        TcpSockfd(int sockfd = defaultsockfd) :_sockfd(sockfd)
        {}
        ~TcpSockfd(){}

        void CreateSocketOrDie() 
        {
            int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if(sockfd < 0)
            {
                std::cout << "创建套接字失败" << std::endl;
                exit(SocketError);
            }
            _sockfd = sockfd;
        }

        void BindSocketOrDie(uint16_t port)
        {
            struct sockaddr_in load;
            memset(&load, 0, sizeof(load));
            load.sin_family = AF_INET;
            load.sin_addr.s_addr = INADDR_ANY;
            load.sin_port = htons(port);

            int ret = ::bind(_sockfd, (const sockaddr *)&load, sizeof(load));
            if(ret != 0)
            {
                std::cout << "绑定套接字失败" << std::endl;
                exit(BindError);
            }
        }

        void ListenSocketOrDie(int backlog = defaultbacklog)
        {
            int ret = ::listen(_sockfd, backlog);
            if(ret != 0)
            {
                std::cout << "监听套接字失败" << std::endl;
                exit(ListenError);
            }
        }

        Socket *AcceptConnection(string *peerip, uint16_t *peerport)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_sockfd, (sockaddr *)&peer, &len);
            if(sockfd < 0)
            {
                std::cout << "接受套接字失败" << std::endl;
                exit(AcceptError);
            }

            *peerip = inet_ntoa(peer.sin_addr);
            *peerport = ntohs(peer.sin_port);
            return new TcpSockfd(sockfd);
        }

        bool ConnectServer(string &serverip, uint16_t serverport)
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(serverip.c_str());
            server.sin_port = htons(serverport);

            int n = ::connect(_sockfd, (sockaddr *)&server, sizeof(server));
            if(n == 0)
                return true;
            return false;
        }

        int GetSockfd()
        {
            return _sockfd;
        }

        void SetSockfd(int &sockfd)
        {
            _sockfd = sockfd;
        }

        void CloseSocket()
        {
            close(_sockfd);
        }

        bool Recv(string *buffer, int size)
        {
            char buff[size];
            int n = recv(_sockfd, &buff, size - 1, 0);
            if(n > 0)
            {
                buff[n] = 0;
                *buffer += buff;
                return true;
            }
            else if(n == 0)
            {
                return false;
            }
            return false;
        }

        void Send(string &send_str)
        {
            send(_sockfd, send_str.c_str(), sizeof(send_str), 0);
        }
        //允许套接字在关闭后立即被重新绑定到相同的地址和端口
        void ReUseAddr()
        {
            int opt = 1;
            setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }
    private:
        int _sockfd;
    };
}